package org.ehe.business.step.test;

import org.ehe.business.step.domain.GeometryAnalysis;
import org.ehe.business.step.domain.ManufacturingEstimate;
import org.ehe.business.step.domain.STEPAnalysisResult;
import org.ehe.business.step.pdf.PDFGenerator;
import org.ehe.business.step.pdf.Render3DModelPreview;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import javax.imageio.ImageIO;

/**
 * @author :zhangnn
 * @className :PDFTestFixture
 * @description: TODO
 * @date 2025-08-06 09:42:56
 */
@Slf4j
@Component
public class PDFTestFixture {
    @Autowired
    private PDFGenerator pdfGenerator;

    @Autowired(required = false)
    private Render3DModelPreview render3DModelPreview;

    /**
     * 创建测试数据并生成PDF
     */
    public String generateTestPDF() {
        try {
            // 创建完整的测试数据
            STEPAnalysisResult testResult = createCompleteTestData();

            // 生成测试3D预览图
            String previewPath = generateTestPreviewImage();
            testResult.setModelPreviewPath(previewPath);

            // 生成PDF
            String pdfPath = pdfGenerator.generatePDFReport(testResult, "test_motor_shaft.step");

            log.info("测试PDF生成成功: {}", pdfPath);
            return pdfPath;

        } catch (Exception e) {
            log.error("生成测试PDF失败", e);
            return null;
        }
    }

    /**
     * 创建完整的测试数据
     */
    private STEPAnalysisResult createCompleteTestData() {
        STEPAnalysisResult result = new STEPAnalysisResult();

        // 基础信息
        result.setRequestId("TEST-" + System.currentTimeMillis());
        result.setFileName("电机轴架测试.step");
        result.setFileSize(187000L); // 约183KB
        result.setStepVersion("AP214");
        result.setCadSoftware("SolidWorks 2023");
        result.setUnit("MILLIMETER");
        result.setComplexity("中等");
        result.setAnalysisTime(LocalDateTime.now());
        result.setProcessingTimeMs(2450L);
        result.setQualityScore(92);

        // 材料信息
        result.setMaterials(Arrays.asList(
            "铝合金 AL6061-T6",
            "不锈钢 304",
            "碳钢 Q235"
        ));

        // 质量问题
        result.setQualityIssues(Arrays.asList(
            "检测到微小的几何间隙",
            "部分圆角半径不一致"
        ));

        // 改进建议
        result.setRecommendations(Arrays.asList(
            "建议统一圆角半径为R2.0mm",
            "优化装配公差配合",
            "考虑增加加强筋结构"
        ));

        // 几何分析
        GeometryAnalysis geometryAnalysis = new GeometryAnalysis();
        geometryAnalysis.setDimensions("70.00 × 104.77 × 232.98 mm");
        geometryAnalysis.setEstimatedVolume(1281491.37);
        geometryAnalysis.setVolumeUnit("mm³");
        geometryAnalysis.setSurfaceComplexityScore(323);

        // 表面类型统计
        Map<String, Integer> surfaceTypes = new HashMap<>();
        surfaceTypes.put("PLANE", 30);
        surfaceTypes.put("CYLINDRICAL_SURFACE", 27);
        surfaceTypes.put("SPHERICAL_SURFACE", 16);
        surfaceTypes.put("CONICAL_SURFACE", 8);
        surfaceTypes.put("B_SPLINE_SURFACE", 12);
        geometryAnalysis.setSurfaceTypes(surfaceTypes);

        result.setGeometryAnalysis(geometryAnalysis);

        // 制造估算
        ManufacturingEstimate manufacturing = new ManufacturingEstimate();
        manufacturing.setEstimatedDays(30);
        manufacturing.setMachiningHours(48);
        manufacturing.setMaterialUtilization(78.5);
        manufacturing.setDifficultyLevel("中等");
        manufacturing.setDifficultyScore(77);
        manufacturing.setEstimatedCost(10863.71);

        // 成本分解
        Map<String, Double> costBreakdown = new HashMap<>();
        costBreakdown.put("材料成本", 1566.12);
        costBreakdown.put("加工费用", 5760.00);
        costBreakdown.put("设备折旧", 720.00);
        costBreakdown.put("人工成本", 1417.01);
        costBreakdown.put("管理费用", 1200.00);
        costBreakdown.put("质检费用", 50.00);
        costBreakdown.put("包装运输", 150.58);
        manufacturing.setCostBreakdown(costBreakdown);

        result.setManufacturingEstimate(manufacturing);

        return result;
    }

    /**
     * 生成测试用3D预览图
     */
    private String generateTestPreviewImage() {
        try {
            String tempDir = System.getProperty("java.io.tmpdir") + "/step_previews";
            File dir = new File(tempDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File imageFile = new File(dir, "test_motor_shaft_preview.png");

            // 创建一个测试3D预览图
            BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = image.createGraphics();

            // 启用抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

            // 背景渐变
            GradientPaint gradient = new GradientPaint(0, 0, Color.WHITE, 0, 600, new Color(240, 248, 255));
            g2d.setPaint(gradient);
            g2d.fillRect(0, 0, 800, 600);

            // 绘制3D电机轴架模型（简化版）
            draw3DMotorShaft(g2d);

            // 添加标题
            g2d.setColor(new Color(41, 128, 185));
            g2d.setFont(new Font("Arial", Font.BOLD, 24));
            FontMetrics fm = g2d.getFontMetrics();
            String title = "电机轴架 3D 预览";
            int x = (800 - fm.stringWidth(title)) / 2;
            g2d.drawString(title, x, 50);

            // 添加尺寸标注
            g2d.setColor(Color.GRAY);
            g2d.setFont(new Font("Arial", Font.PLAIN, 12));
            g2d.drawString("尺寸: 70×104.77×232.98mm", 20, 580);
            g2d.drawString("材质: 铝合金 AL6061-T6", 300, 580);
            g2d.drawString("复杂度: 中等", 600, 580);

            g2d.dispose();

            // 保存图片
            ImageIO.write(image, "PNG", imageFile);

            log.info("生成测试3D预览图: {}", imageFile.getAbsolutePath());
            return imageFile.getAbsolutePath();

        } catch (Exception e) {
            log.error("生成测试3D预览图失败", e);
            return null;
        }
    }

    /**
     * 绘制简化的3D电机轴架
     */
    private void draw3DMotorShaft(Graphics2D g2d) {
        // 设置基本颜色
        Color baseColor = new Color(180, 200, 220);
        Color darkColor = new Color(120, 140, 160);
        Color lightColor = new Color(220, 230, 240);

        // 绘制主体部分（等轴测投影）
        int centerX = 400;
        int centerY = 300;

        // 主轴体
        g2d.setColor(baseColor);
        int[] mainBodyX = {centerX-100, centerX+100, centerX+150, centerX-50};
        int[] mainBodyY = {centerY-50, centerY-50, centerY-80, centerY-80};
        g2d.fillPolygon(mainBodyX, mainBodyY, 4);

        // 主轴体正面
        g2d.setColor(lightColor);
        int[] frontX = {centerX-100, centerX+100, centerX+100, centerX-100};
        int[] frontY = {centerY-50, centerY-50, centerY+50, centerY+50};
        g2d.fillPolygon(frontX, frontY, 4);

        // 主轴体侧面
        g2d.setColor(darkColor);
        int[] sideX = {centerX+100, centerX+150, centerX+150, centerX+100};
        int[] sideY = {centerY-50, centerY-80, centerY+20, centerY+50};
        g2d.fillPolygon(sideX, sideY, 4);

        // 轴承座1
        g2d.setColor(new Color(200, 180, 160));
        g2d.fillOval(centerX-120, centerY-30, 60, 60);
        g2d.setColor(new Color(160, 140, 120));
        g2d.fillOval(centerX-110, centerY-20, 40, 40);

        // 轴承座2
        g2d.setColor(new Color(200, 180, 160));
        g2d.fillOval(centerX+60, centerY-30, 60, 60);
        g2d.setColor(new Color(160, 140, 120));
        g2d.fillOval(centerX+70, centerY-20, 40, 40);

        // 连接法兰
        g2d.setColor(new Color(190, 210, 200));
        int[] flangeX = {centerX-80, centerX-60, centerX-40, centerX-60};
        int[] flangeY = {centerY+50, centerY+50, centerY+80, centerY+80};
        g2d.fillPolygon(flangeX, flangeY, 4);

        // 螺栓孔
        g2d.setColor(Color.BLACK);
        g2d.fillOval(centerX-75, centerY+60, 8, 8);
        g2d.fillOval(centerX-55, centerY+60, 8, 8);

        // 边框线条
        g2d.setColor(new Color(80, 100, 120));
        g2d.setStroke(new BasicStroke(2));
        g2d.drawPolygon(frontX, frontY, 4);
        g2d.drawPolygon(sideX, sideY, 4);
        g2d.drawPolygon(mainBodyX, mainBodyY, 4);

        // 中心线
        g2d.setColor(Color.RED);
        g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
            10.0f, new float[]{5.0f, 5.0f}, 0.0f));
        g2d.drawLine(centerX-150, centerY, centerX+150, centerY);

        // 尺寸标注线
        g2d.setColor(new Color(100, 100, 100));
        g2d.setStroke(new BasicStroke(1));
        g2d.drawLine(centerX-100, centerY+100, centerX+100, centerY+100);
        g2d.drawLine(centerX-100, centerY+95, centerX-100, centerY+105);
        g2d.drawLine(centerX+100, centerY+95, centerX+100, centerY+105);

        // 标注文字
        g2d.setFont(new Font("Arial", Font.PLAIN, 10));
        g2d.drawString("232.98mm", centerX-20, centerY+120);
    }

    /**
     * 诊断和修复方法
     */
    public void diagnosePDFIssues() {
        log.info("=== PDF生成问题诊断 ===");

        // 1. 检查字体
        try {
            com.itextpdf.kernel.font.PdfFont testFont =
                com.itextpdf.kernel.font.PdfFontFactory.createFont(
                    com.itextpdf.io.font.constants.StandardFonts.HELVETICA);
            log.info("✓ 字体初始化正常");
        } catch (Exception e) {
            log.error("✗ 字体初始化失败: {}", e.getMessage());
        }

        // 2. 检查输出目录
        File outputDir = new File("/Users/zhangenen/Downloads/pdf/");
        if (outputDir.exists() && outputDir.canWrite()) {
            log.info("✓ 输出目录可访问: {}", outputDir.getAbsolutePath());
        } else {
            log.error("✗ 输出目录不可访问，创建目录: {}", outputDir.getAbsolutePath());
            outputDir.mkdirs();
        }

        // 3. 检查3D渲染服务
        if (render3DModelPreview != null) {
            boolean freecadAvailable = render3DModelPreview.isFreeCADAvailable();
            if (freecadAvailable) {
                log.info("✓ FreeCAD可用");
            } else {
                log.warn("⚠ FreeCAD不可用，将使用占位图");
            }
        } else {
            log.warn("⚠ 3D渲染服务未注入");
        }

        // 4. 生成测试报告
        try {
            String testPDFPath = generateTestPDF();
            if (testPDFPath != null) {
                log.info("✓ 测试PDF生成成功: {}", testPDFPath);

                // 验证文件
                File pdfFile = new File(testPDFPath);
                if (pdfFile.exists() && pdfFile.length() > 10000) {
                    log.info("✓ PDF文件大小正常: {} bytes", pdfFile.length());
                } else {
                    log.error("✗ PDF文件异常: 大小={} bytes", pdfFile.length());
                }
            } else {
                log.error("✗ 测试PDF生成失败");
            }
        } catch (Exception e) {
            log.error("✗ PDF生成测试异常", e);
        }

        log.info("=== 诊断完成 ===");
    }

    /**
     * 修复建议
     */
    public void printFixSuggestions() {
        log.info("=== PDF问题修复建议 ===");
        log.info("1. 字段标签问题修复:");
        log.info("   - 确保addEnhancedTableRow方法正确传入header参数");
        log.info("   - 检查字体设置和显示逻辑");
        log.info("   - 验证表格单元格布局");

        log.info("2. 3D预览图问题修复:");
        log.info("   - 安装FreeCAD: https://www.freecadweb.org/downloads.php");
        log.info("   - 配置系统PATH环境变量");
        log.info("   - 或使用generateTestPreviewImage()生成测试图片");

        log.info("3. 数据完整性检查:");
        log.info("   - 确保STEPAnalysisResult所有字段都有值");
        log.info("   - 添加null值检查和默认值");
        log.info("   - 使用createCompleteTestData()生成完整测试数据");

        log.info("4. 调试步骤:");
        log.info("   - 运行diagnosePDFIssues()诊断问题");
        log.info("   - 使用测试数据generateTestPDF()验证修复");
        log.info("   - 检查日志输出定位具体问题");
    }
}
